package com.kla.power.controller;


import com.kla.power.entity.FileEntity;
import com.kla.power.util.ConstUtil;
import com.kla.power.util.FileUtil;
import com.kla.power.util.ResultBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件表 前端控制器
 * </p>
 *
 * @author WuZH
 * @since 2024-08-06
 */
@RestController
@RequestMapping ( "/file" )
@CrossOrigin ( value = "*", maxAge = 3600 )
public class FileController {

    @Value ( "${filePath}" )
    private String filePath;

    /**
     * 通用文件上传
     *
     * @param multipartFiles：文件对象
     * @return
     */
    @RequestMapping ( "uploadFile" )
    public ResultBody uploadFile ( List<MultipartFile> multipartFiles ) {
        List<FileEntity> fileEntities = new ArrayList<> ();
        for ( MultipartFile file : multipartFiles ) {
            String fileName = FileUtil.fileNameTreated ( file.getOriginalFilename () );
            try {
                FileUtil.upload ( file, filePath, fileName );
            } catch ( Exception e ) {
                e.printStackTrace ();
            }
            FileEntity fileEntity = new FileEntity ();
            fileEntity.setDiskUrl ( filePath + "/" + fileName );
            fileEntity.setFileUrl ( ConstUtil.DO_MAIN + "/img/" + fileName );
            fileEntities.add ( fileEntity );
        }
        return ResultBody.success ( fileEntities );
    }


    /**
     * 上传单个文件，不入库，直接返回URL地址
     *
     * @param multipartFile
     */
    @RequestMapping ( "uploadSingleFile" )
    public ResultBody uploadFile ( MultipartFile multipartFile ) {
        String fileName = FileUtil.fileNameTreated ( multipartFile.getOriginalFilename () );
        try {
            FileUtil.upload ( multipartFile, filePath, fileName );
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return ResultBody.success ( ConstUtil.DO_MAIN + "/img/" + fileName );
    }

}
